var userRegex = /^([A-Za-z0-9]{2,16}$)|(^[\u4E00-\u9FA5]{2,8})$/;
var passwordRegex = /^[0-9_a-zA-Z]{6,20}$/;
var isEmpty = true;
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

function decodeUTF8(str){  
    return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2) {
        return String.fromCharCode(parseInt($2,16));
    });
}

function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
function checkUserName() {
    var userName = $("#userName").val();
    if (!userRegex.test(userName)) {
        $("#wrong_img1").show();
        $("#error_tip").css("visibility", "visible");
        $("#error_tip").html("Username format is wrong!");
        return true;
    } else {
        $("#wrong_img1").hide();
        $("#error_tip").css("visibility", "hidden");
        $("#error_tip").html("");
        return false;
    }
}
function checkPassword() {
    var password = $("#password").val();
    if (!passwordRegex.test(password)) {
        $("#wrong_img2").show();
        $("#error_tip").css("visibility", "visible");
        $("#error_tip").html("Password format is wrong! 6-20 characters");
        return true;
    } else {
        $("#wrong_img2").hide();
        $("#error_tip").css("visibility", "hidden");
        $("#error_tip").html("");
        return false;
    }
}
$(function() {
    $("#userName").blur(function() {
        checkUserName();
    });
    $("#password").blur(function() {
        checkPassword();
    });
    $("#submit_btn").click(function() {
        var f1 = checkUserName();
        var f2 = checkPassword();
        if (f1) {
            checkUserName();
            return;
        }
        if (f2) {
            checkPassword();
            return;
        }
        var remember = $("remember").val();
        if (!remember) {
            delCookie("userName");
            delCookie("password");
        }
        $("#login_form").submit();
    });
    $(document).keypress(function(e) {
        if (e.which == 13) {
            $("#submit_btn").click();
        }
    });

    var cookieU = document.cookie.split(";")[0].split("=")[1];
    var cookieP = document.cookie.split(";")[1].split("=")[1];
    $("#userName").val(decodeURIComponent(cookieU));
    $("#password").val(decodeURIComponent(cookieP));

})
